package com.academic.system.controller;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.academic.system.controller.request.AchievementRequest;
import com.academic.system.model.Achievement;
import com.academic.system.model.User;
import com.academic.system.security.UserDetailsImpl;
import com.academic.system.service.AchievementService;
import com.academic.system.service.UserService;

/**
 * 学生专用控制器
 */
@RestController
@RequestMapping("/api/student")
@CrossOrigin(origins = "*", maxAge = 3600)
public class StudentController {

    @Autowired
    private AchievementService achievementService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 获取当前学生的所有成果
     */
    @GetMapping("/achievements")
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<?> getMyAchievements(
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String type) {
        
        // 获取当前登录的学生信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        List<Achievement> achievements;
        
        if (status != null && !status.isEmpty()) {
            achievements = achievementService.findByStudentIdAndStatus(userDetails.getId(), status);
        } else {
            achievements = achievementService.findByStudentId(userDetails.getId());
        }
        
        // 如果指定了类型，进行过滤
        if (type != null && !type.isEmpty()) {
            achievements = achievements.stream()
                .filter(a -> type.equals(a.getType()))
                .collect(Collectors.toList());
        }
        
        List<Map<String, Object>> result = achievements.stream()
            .map(this::convertToDto)
            .collect(Collectors.toList());
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取成果统计信息
     */
    @GetMapping("/achievements/stats")
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<?> getAchievementStats() {
        // 获取当前登录的学生信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        Map<String, Integer> stats = achievementService.getStudentAchievementStats(userDetails.getId());
        
        return ResponseEntity.ok(stats);
    }
    
    /**
     * 根据ID获取成果详情
     */
    @GetMapping("/achievements/{id}")
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<?> getAchievementById(@PathVariable Integer id) {
        // 获取当前登录的学生信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        Achievement achievement = achievementService.findById(id);
        
        if (achievement == null) {
            return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(Map.of("message", "成果不存在"));
        }
        
        // 验证该成果是否属于当前学生
        if (achievement.getStudent() == null || !achievement.getStudent().getId().equals(userDetails.getId())) {
            return ResponseEntity
                .status(HttpStatus.FORBIDDEN)
                .body(Map.of("message", "无权查看非自己的成果"));
        }
        
        return ResponseEntity.ok(convertToDto(achievement));
    }
    
    /**
     * 创建新成果
     */
    @PostMapping("/achievements")
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<?> createAchievement(@Valid @RequestBody AchievementRequest request) {
        // 获取当前登录的学生信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        User student = userService.findById(userDetails.getId());
        if (student == null) {
            return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body(Map.of("message", "学生信息不存在"));
        }
        
        // 创建新成果
        Achievement achievement = new Achievement();
        achievement.setTitle(request.getTitle());
        achievement.setType(request.getType());
        achievement.setDescription(request.getDescription());
        achievement.setAuthors(request.getAuthors());
        achievement.setJournal(request.getJournal());
        achievement.setPatentNo(request.getPatentNo());
        achievement.setProjectNo(request.getProjectNo());
        
        // 处理发表日期
        if (request.getPublishDate() != null && !request.getPublishDate().isEmpty()) {
            LocalDateTime publishDate = LocalDateTime.parse(request.getPublishDate(), 
                DateTimeFormatter.ISO_DATE_TIME);
            achievement.setPublishDate(publishDate);
        }
        
        achievement.setAttachmentUrl(request.getAttachmentUrl());
        achievement.setStudent(student);
        
        Achievement savedAchievement = achievementService.createAchievement(achievement);
        
        return ResponseEntity.status(HttpStatus.CREATED).body(convertToDto(savedAchievement));
    }
    
    /**
     * 更新成果
     */
    @PutMapping("/achievements/{id}")
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<?> updateAchievement(
            @PathVariable Integer id, 
            @Valid @RequestBody AchievementRequest request) {
        
        // 获取当前登录的学生信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        Achievement achievement = achievementService.findById(id);
        
        if (achievement == null) {
            return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(Map.of("message", "成果不存在"));
        }
        
        // 验证该成果是否属于当前学生
        if (achievement.getStudent() == null || !achievement.getStudent().getId().equals(userDetails.getId())) {
            return ResponseEntity
                .status(HttpStatus.FORBIDDEN)
                .body(Map.of("message", "无权修改非自己的成果"));
        }
        
        // 只有待审核状态的成果才能修改
        if (!"待审核".equals(achievement.getStatus())) {
            return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body(Map.of("message", "只有待审核状态的成果才能修改"));
        }
        
        // 更新成果信息
        achievement.setTitle(request.getTitle());
        achievement.setType(request.getType());
        achievement.setDescription(request.getDescription());
        achievement.setAuthors(request.getAuthors());
        achievement.setJournal(request.getJournal());
        achievement.setPatentNo(request.getPatentNo());
        achievement.setProjectNo(request.getProjectNo());
        
        // 处理发表日期
        if (request.getPublishDate() != null && !request.getPublishDate().isEmpty()) {
            LocalDateTime publishDate = LocalDateTime.parse(request.getPublishDate(), 
                DateTimeFormatter.ISO_DATE_TIME);
            achievement.setPublishDate(publishDate);
        }
        
        achievement.setAttachmentUrl(request.getAttachmentUrl());
        
        Achievement updatedAchievement = achievementService.updateAchievement(achievement);
        
        return ResponseEntity.ok(convertToDto(updatedAchievement));
    }
    
    /**
     * 删除成果
     */
    @DeleteMapping("/achievements/{id}")
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<?> deleteAchievement(@PathVariable Integer id) {
        // 获取当前登录的学生信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        Achievement achievement = achievementService.findById(id);
        
        if (achievement == null) {
            return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(Map.of("message", "成果不存在"));
        }
        
        // 验证该成果是否属于当前学生
        if (achievement.getStudent() == null || !achievement.getStudent().getId().equals(userDetails.getId())) {
            return ResponseEntity
                .status(HttpStatus.FORBIDDEN)
                .body(Map.of("message", "无权删除非自己的成果"));
        }
        
        // 只有待审核状态的成果才能删除
        if (!"待审核".equals(achievement.getStatus())) {
            return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body(Map.of("message", "只有待审核状态的成果才能删除"));
        }
        
        achievementService.deleteAchievement(id);
        
        return ResponseEntity.ok(Map.of("message", "成果已删除"));
    }
    
    /**
     * 将成果实体转换为DTO
     */
    private Map<String, Object> convertToDto(Achievement achievement) {
        Map<String, Object> dto = new HashMap<>();
        dto.put("id", achievement.getId());
        dto.put("title", achievement.getTitle());
        dto.put("type", achievement.getType());
        dto.put("description", achievement.getDescription());
        dto.put("authors", achievement.getAuthors());
        dto.put("journal", achievement.getJournal());
        dto.put("patentNo", achievement.getPatentNo());
        dto.put("projectNo", achievement.getProjectNo());
        dto.put("publishDate", achievement.getPublishDate());
        dto.put("status", achievement.getStatus());
        dto.put("attachmentUrl", achievement.getAttachmentUrl());
        dto.put("createdAt", achievement.getCreatedAt());
        dto.put("updatedAt", achievement.getUpdatedAt());
        dto.put("comments", achievement.getComments());
        
        if (achievement.getStudent() != null) {
            Map<String, Object> student = new HashMap<>();
            student.put("id", achievement.getStudent().getId());
            student.put("username", achievement.getStudent().getUsername());
            student.put("realName", achievement.getStudent().getRealName());
            dto.put("student", student);
        }
        
        if (achievement.getReviewer() != null) {
            Map<String, Object> reviewer = new HashMap<>();
            reviewer.put("id", achievement.getReviewer().getId());
            reviewer.put("username", achievement.getReviewer().getUsername());
            reviewer.put("realName", achievement.getReviewer().getRealName());
            dto.put("reviewer", reviewer);
        }
        
        return dto;
    }
} 